package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.model.IPAddress;
import com.conversationboard.model.User;

@WebServlet(name = "AdminGetIPsForUserControllerServlet", urlPatterns = "/Admin/AdminGetIPsForUserControllerServlet")
public class AdminGetIPsForUserControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -4074014664113997893L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {
			User viewingUser = User.get(request.getUserPrincipal().getName());

			if (!viewingUser.isSiteAdmin()) {
				return;
			}

			if (!SecurityChecks.passes(request, viewingUser, this)) {
				return;
			}

			User user = User.get(request.getParameter("loginId"));
			int days = Integer.parseInt(request.getParameter("days"));

			List<IPAddress> distinctIPs = user.getDistinctIPs(days);

			request.setAttribute("user", user);
			request.setAttribute("distinctIPs", distinctIPs);

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/Admin/view-distinct-ips.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}
}
